package com.billsharing.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AndroidResponse
 */
@WebServlet("/AndroidResponse")
public class AndroidResponse extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public int uid, uid2;
	String json;
	Connection conn;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/x-json;charset=UTF-8");
		String un, pw;
		un = request.getParameter("username");
		pw = request.getParameter("password");
		Connection conn = null;

		DbConnect dbconn = new DbConnect();
		conn = dbconn.getConnection();
		try {
			Statement s = conn.createStatement();
			s.executeQuery("select uid,username,pwd from Users");
			ResultSet rs = s.getResultSet();

			while (rs.next()) {

				String usname = rs.getString("username");
				String pass = rs.getString("pwd");
				String uid1 = rs.getString("uid");
				
				if (un.equals(usname) && pw.equals(pass)) {
					System.out.println("true");
					uid = Integer.parseInt(uid1);
					System.out.println("Userid is" + uid);
					User user = new User(uid);
					user.setUserName(usname);
					ToJson jsonObj = new ToJson(user);
					json = jsonObj.getJsonString();
					break;
				} else {
					json = "false1";

				}

			}
			System.out.println("JSON objects in login"+json);
			out.print(json);
			dbconn.close();

		} catch (Exception e) {
			out.print(e);

		}

	}
}
